// 加载名片夹数据
function loadFolders() {
    showLoader();
    
    // 定义演示数据，以便在API失败时使用
    const demoFolders = [
        { folder_id: 1, folder_name: "我的名片夹", user_id: 1, card_count: 15 },
        { folder_id: 2, folder_name: "商业伙伴", user_id: 1, card_count: 8 },
        { folder_id: 3, folder_name: "工作联系人", user_id: 1, card_count: 12 }
    ];
    
    fetch('CardFolderServlet?action=getFoldersByUser')
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            hideLoader();
            
            // 确保数据是数组格式
            if (Array.isArray(data)) {
                renderFolders(data);  // 渲染文件夹
                updateFolderSelects(data);  // 更新选择框（假设有这个功能）
            } else if (data && typeof data === 'object' && data.folders && Array.isArray(data.folders)) {
                renderFolders(data.folders);  // 如果数据在子对象中
                updateFolderSelects(data.folders);
            } else {
                console.error('服务器返回的数据格式不正确:', data);
                showMessage('数据格式不正确，使用演示数据', 'error');
                renderFolders(demoFolders);  // 使用演示数据
                updateFolderSelects(demoFolders);
            }
        })
        .catch(error => {
            console.error('加载名片夹失败:', error);
            hideLoader();
            
            // API调用失败时直接使用演示数据
            showMessage('加载名片夹失败，使用演示数据', 'error');
            renderFolders(demoFolders);  // 使用演示数据
            updateFolderSelects(demoFolders);
        });
}

// 更新所有下拉框中的名片夹选项
function updateFolderSelects(folders) {
    const selects = ['cardFolder', 'batchCardFolder', 'importFolder'];
    
    selects.forEach(selectId => {
        const select = document.getElementById(selectId);
        if (!select) return; // 如果元素不存在，跳过
        
        select.innerHTML = '';
        
        folders.forEach(folder => {
            const option = document.createElement('option');
            option.value = folder.folderId;
            option.textContent = folder.folderName || '无名文件夹';  // 确保有文件夹名称
            select.appendChild(option);
        });
        
        // 如果有当前名片夹，则选中它
        if (currentFolder) {
            select.value = currentFolder;
        }
    });
}

// 渲染名片夹
function renderFolders(folders) {
    const container = document.getElementById('cardFolders');
    const addButton = document.getElementById('addFolderBtn');
    
    // 确保folders是数组
    if (!Array.isArray(folders)) {
        console.error('renderFolders接收到非数组数据:', folders);
        folders = []; // 使用空数组防止错误
    }
    
    // 清空容器，但保留添加按钮
    container.innerHTML = '';
    container.appendChild(addButton);
    
    folders.forEach((folder, index) => {
        const folderEl = document.createElement('div');
        folderEl.className = 'card-folder float-animation';
        folderEl.dataset.id = folder.folderId;
        folderEl.dataset.name = folder.folderName;
        
        // 设置随机的动画延迟
        folderEl.style.animationDelay = index * 0.2 + 's';
        
        // 确保文件夹名称不为空
        folderEl.textContent = folder.folderName || '无名文件夹';
        
        // 插入到添加按钮之前
        container.insertBefore(folderEl, addButton);
        
        // 添加点击事件
        folderEl.addEventListener('click', () => {
            // 移除其他文件夹的active状态
            document.querySelectorAll('.card-folder').forEach(f => {
                f.classList.remove('active');
            });
            
            // 为当前文件夹添加active状态
            folderEl.classList.add('active');
            
            loadCards(folder.folderId);
            currentFolder = folder.folderId;
        });
        
        // 添加右键菜单事件
        folderEl.addEventListener('contextmenu', (e) => {
            e.preventDefault();
            
            // 清除原有菜单项
            const contextMenu = document.getElementById('contextMenu');
            contextMenu.innerHTML = '';
            
            // 添加名片夹菜单项
            const menuItems = [
                { id: 'ctxOpen', icon: 'folder-open', text: '打开' },
                { id: 'ctxRename', icon: 'edit', text: '重命名' },
                { id: 'ctxExport', icon: 'file-export', text: '导出' },
                { id: 'ctxDelete', icon: 'trash', text: '删除' }
            ];
            
            menuItems.forEach(item => {
                const link = document.createElement('a');
                link.id = item.id;
                link.innerHTML = '<i class="fas fa-' + item.icon + ' me-2"></i> ' + item.text;
                contextMenu.appendChild(link);
                
                link.addEventListener('click', () => {
                    handleFolderContextMenu(item.id, folder.folderId, folder.folderName);
                });
            });
            
            // 设置菜单位置
            contextMenu.style.top = e.pageY + 'px';
            contextMenu.style.left = e.pageX + 'px';
            contextMenu.style.display = 'block';
        });
    });
    
    // 保存文件夹数据到全局变量
    window.folders = folders;
    
    // 如果没有文件夹，显示一个提示
    if (folders.length === 0) {
        const emptyMessage = document.createElement('div');
        emptyMessage.className = 'empty-message';
        emptyMessage.textContent = '没有名片夹，请点击"新建名片夹"创建';
        emptyMessage.style.padding = '10px';
        emptyMessage.style.color = '#666';
        container.insertBefore(emptyMessage, addButton);
    }
}

// 处理名片夹右键菜单
function handleFolderContextMenu(action, folderId, folderName) {
    document.getElementById('contextMenu').style.display = 'none';
    
    switch (action) {
        case 'ctxOpen':
            // 移除其他文件夹的active状态
            document.querySelectorAll('.card-folder').forEach(f => {
                f.classList.remove('active');
            });
            
            // 为当前文件夹添加active状态
            const targetFolder = document.querySelector(`[data-id="${folderId}"]`);
            if (targetFolder) {
                targetFolder.classList.add('active');
            }
            
            loadCards(folderId);
            currentFolder = folderId;
            break;
        case 'ctxRename':
            document.getElementById('folderName').value = folderName;
            document.getElementById('folderId').value = folderId;
            document.querySelector('#folderModal .modal-header h2').textContent = '重命名名片夹';
            showModal('folderModal');
            break;
        case 'ctxExport':
            document.getElementById('exportFilename').value = folderName + '_' + new Date().toISOString().slice(0, 10).replace(/-/g, '');
            document.getElementById('exportFolderId').value = folderId;
            document.getElementById('exportCardIds').value = '';
            showModal('exportModal');
            break;
        case 'ctxDelete':
            if (confirm('确定要删除名片夹"' + folderName + '"吗？名片夹内的所有名片也将被移至回收站。')) {
                deleteFolder(folderId);
            }
            break;
    }
}

// 创建新名片夹
function createFolder(folderName) {
    // 检查权限
    if (!checkPermissionBeforeAction('create_folder', '创建名片夹')) {
        return;
    }
    
    showLoader();
    
    const formData = new FormData();
    formData.append('folder_name', folderName);
    formData.append('user_id', currentUserId);
    
    fetch('CardFolderServlet?action=addFolder', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        console.log('创建名片夹响应状态:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('创建名片夹响应数据:', data);
        hideLoader();
        
        if (data.success) {
            loadFolders(); // 重新加载名片夹列表
            showMessage('名片夹"' + folderName + '"创建成功', 'success');
        } else {
            throw new Error(data.message || '创建名片夹失败');
        }
    })
    .catch(error => {
        hideLoader();
        console.error('创建名片夹失败:', error);
        showMessage('创建名片夹失败: ' + error.message, 'error');
    });
}

// 更新名片夹 - 修复编码问题
function updateFolder(folderId, folderName) {
    console.log('updateFolder调用，参数:', { folderId, folderName });
    
    // 检查权限
    if (!checkPermissionBeforeAction('edit_folder', '编辑名片夹')) {
        return;
    }
    
    showLoader();
    
    // 方法1：使用URLSearchParams发送application/x-www-form-urlencoded格式
    const params = new URLSearchParams();
    params.append('action', 'updateFolder');
    params.append('folder_id', folderId.toString());
    params.append('folder_name', folderName);
    
    fetch('CardFolderServlet', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: params
    })
    .then(response => {
        console.log('更新名片夹响应状态:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('更新名片夹响应数据:', data);
        hideLoader();
        
        if (data.success) {
            loadFolders(); // 重新加载名片夹列表
            showMessage('名片夹更新为"' + folderName + '"', 'success');
        } else {
            throw new Error(data.message || '更新名片夹失败');
        }
    })
    .catch(error => {
        hideLoader();
        console.error('更新名片夹失败:', error);
        showMessage('更新名片夹失败: ' + error.message, 'error');
    });
}

// 删除名片夹
function deleteFolder(folderId) {
    // 检查权限
    if (!checkPermissionBeforeAction('delete_folder', '删除名片夹')) {
        return;
    }
    
    showLoader();
    
    const formData = new FormData();
    formData.append('folder_id', folderId);
    
    fetch('CardFolderServlet?action=deleteFolder', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        console.log('删除名片夹响应状态:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('删除名片夹响应数据:', data);
        hideLoader();
        
        if (data.success) {
            // 如果当前删除的是正在查看的名片夹，清空当前选择
            if (currentFolder === folderId) {
                currentFolder = null;
                // 清空卡片列表
                document.getElementById('cardList').innerHTML = '';
                document.getElementById('cardTableBody').innerHTML = '';
                
                // 移除所有文件夹的active状态
                document.querySelectorAll('.card-folder').forEach(f => {
                    f.classList.remove('active');
                });
            }
            
            loadFolders();
            showMessage('名片夹已移到回收站', 'success');
        } else {
            throw new Error(data.message || '删除名片夹失败');
        }
    })
    .catch(error => {
        hideLoader();
        console.error('删除名片夹失败:', error);
        showMessage('删除名片夹失败: ' + error.message, 'error');
    });
}